//
//  QuickViewController.m
//  MJVideoPlayer
//
//  Created by 梅杰 on 16/8/13.
//  Copyright © 2016年 梅杰. All rights reserved.
//

#import "QuickViewController.h"
#import "MJVideo.h"
#import "MJVideoView.h"
#import "MRVLCPlayer.h"
#import "MJCollectHeadView.h"
#import <Photos/Photos.h>
//#import <QuickLook/QuickLook.h>
@interface QuickViewController () <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,weak) UICollectionView *collectView;

@property (nonatomic,strong) NSArray *dataArray;
@property (nonatomic,strong) NSArray *albumVideos;
@property (nonatomic,weak) MRVLCPlayer *VLCPlayer;
@end

@implementation QuickViewController

static NSString *const cellId = @"cellId";

- (void)viewDidLoad{
    [super viewDidLoad];
    [self setWeight];

}



- (NSArray *)loadVideos {
    // 所有视频
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum
        subtype:PHAssetCollectionSubtypeSmartAlbumVideos options:nil];
    PHAssetCollection *videoCollection = smartAlbums[0];//所有视频相册
    PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:videoCollection options:nil];
    
    PHImageManager *imageManager = [[PHImageManager alloc] init];
    NSMutableArray *videoArray = [NSMutableArray arrayWithCapacity:0];
    for (PHAsset *videoAsset in fetchResult) {
        [imageManager requestAVAssetForVideo:videoAsset options:PHVideoRequestOptionsVersionCurrent resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            //                NSLog(@"%@",[asset description]);
            AVURLAsset *videoAsset = (AVURLAsset *)asset;
            NSLog(@"%@",videoAsset.URL);
            if (videoAsset) {
                MJVideo *video = [[MJVideo alloc] init];
                video.url = videoAsset.URL;
                NSString *videoName = [[[videoAsset.URL absoluteString] lastPathComponent] stringByDeletingPathExtension];
                video.name = videoName;
                [videoArray addObject:video];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectView reloadSections:[[NSIndexSet alloc] initWithIndex:1]];
            });
        }];
    }
    
    return videoArray;
}
- (NSArray *)albumVideos{
    if (!_albumVideos) {
        _albumVideos = [self loadVideos];
    }
    return _albumVideos;
}
//获得document下的所有视频文件


- (NSArray *) getDocumentVideos{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    
//    NSString *test = [documentsDirectory stringByAppendingPathComponent:@"test"];
//    [fileManager createDirectoryAtPath:test withIntermediateDirectories:YES attributes:nil error:nil];
    NSMutableArray *VideoArray = [NSMutableArray array];
    for (NSString *path in contents) {
        NSString *contentPath = [documentsDirectory stringByAppendingPathComponent:path];
        NSURL *url = [NSURL fileURLWithPath:contentPath];

        
        NSString *videoName = [path stringByDeletingPathExtension];
        MJVideo *video = [[MJVideo alloc] init];
        BOOL isDirectory = NO;
        [fileManager fileExistsAtPath:contentPath isDirectory:&isDirectory];
        if (url && !isDirectory) {
            
            video.url = url;
            video.name = videoName;
            
            [VideoArray addObject:video];
        }
    }
    
    return VideoArray;
}

- (NSArray *)dataArray{
    if (!_dataArray) {
//        NSString *path = [[NSBundle mainBundle] pathForResource:@"test.mp4" ofType:nil];
//        NSURL *url = [NSURL fileURLWithPath:path];
//        MJVideo *vid = [[MJVideo alloc] init];
//        vid.url = url;
//        vid.name = @"test";
//        NSArray *array = @[vid,vid,vid,vid,vid,vid,vid,vid,vid,vid,vid,vid];
//        _dataArray = array;
        _dataArray = [self getDocumentVideos];
    }
    return _dataArray;
}

- (void) setWeight{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    UICollectionView *colView = [[UICollectionView alloc] initWithFrame:CGRectNull collectionViewLayout:flowLayout];
    [self.view addSubview:colView];
    self.collectView = colView;
    colView.backgroundColor = [UIColor whiteColor];
    [colView registerClass:[MJVideoView class] forCellWithReuseIdentifier:cellId];
    
    [colView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets = UIEdgeInsetsMake(0, 0, 0, 0);
    }];
    colView.delegate = self;
    colView.dataSource = self;
    
}

#pragma mark collectionview的代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
         return self.dataArray.count;
    }else if (section == 1){
        return self.albumVideos.count;
    }
    return 0;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MJVideoView *videoCell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    if (indexPath.section == 0) {
        videoCell.aVideo = ((MJVideo *)self.dataArray[indexPath.item]);
    }
    if (indexPath.section == 1) {
        videoCell.aVideo = ((MJVideo *)self.albumVideos[indexPath.item]);
    }
    return videoCell;
}

-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    
    CGSize size = {kScreenWidth, 50};
    if ([collectionView numberOfItemsInSection:section] <= 0) {
        size = CGSizeZero;
    }
    return size;
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    // 注册表头
    [collectionView registerClass:[MJCollectHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
    
    // 初始化表头
    MJCollectHeadView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
    NSArray * array = @[@"文档视频",@"相册视频"];
    headerView.titleLbl.text = array[indexPath.section];
    headerView.titleLbl.textColor = [UIColor blackColor];
    headerView.backgroundColor = [UIColor lightGrayColor];
    headerView.titleLbl.font = [UIFont systemFontOfSize:18];
    return headerView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    MJVideo *video = nil;
    if (indexPath.section == 0) {
        video = self.dataArray[indexPath.item];
    }
    if (indexPath.section == 1) {
        video = self.albumVideos[indexPath.item];
    }
    
    MRVLCPlayer *player = [[MRVLCPlayer alloc] init];
    CGRect bounds = CGRectZero;
    //判断屏幕方向
//    if(UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])){
//        bounds = CGRectMake(0, 0, self.view.bounds.size.height, self.view.bounds.size.height / 16 * 9);
//    }else{
    bounds = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width / 16 * 9);
//    }
//    player.frame = CGRectMake(0, 0, self.view.window.bounds.size.width, self.view.window.bounds.size.height);
    player.bounds = bounds;
    player.center = self.view.center;
    
    player.mediaURL = video.url;
//    player.isFullscreenModel = YES;

    if (self.VLCPlayer) {
        [self.VLCPlayer dismiss];
    }
    [player showInView:self.view.window];

    self.VLCPlayer = player;


}
#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return (CGSize){100,100};
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}
@end
